<script setup>
import {ref} from 'vue';
import webConfig from "@/GlobalParas.js";
import axios from "axios";

const value = ref([]);
let treeData = ref([]);

let userDeptId = localStorage.getItem("deptId");
let depts = [];
let deptUrl = webConfig.postUrl + '/dept/getAllDepts';

let emit = defineEmits(["optionSelected"])

axios.post(deptUrl).then((res) => {
  depts = res.data;//获取所有部门
  getDeptNodes(depts, null, userDeptId)
  console.log(treeData.value);
})

function itemSelected(itemValues, items){
  // console.log(items)
  emit("optionSelected", items)
}

function getDeptNodes(depts, currentDept, parentId) {
  // console.log(parentId)
  let subDepts;
  if (currentDept === null) {
    subDepts = depts.filter((item) => {
      return item.tableKey === parentId;
    })
  } else {
    subDepts = depts.filter((item) => {
      return item.parentDeptId === parentId;
    })
  }

  // subDepts = depts.filter((item) => {
  //   return item.parentDeptId === parentId;
  // })

  subDepts.sort((a, b) => a.sort - b.sort);//按照部门排序顺序显示
  // console.log(subDepts);


  subDepts.forEach((item) => {
    let treeNode = {};
    treeNode.label = item.deptName;
    treeNode.value = item.tableKey;
    treeNode.nodeType = "dept";
    treeNode.children = [];

    if (currentDept === null) {
      treeData.value.push(treeNode);
    } else {
      currentDept.children.push(treeNode)
    }
    getDeptNodes(depts, treeNode, treeNode.value);
  })
}

</script>

<template>
  <a-cascader
      v-model:value="value"
      :options="treeData"
      placeholder="请选择部门……"
      @change="itemSelected"
  />
</template>

<style scoped>

</style>